<template>
  <el-container v-loading="loading">
    <el-container>
      <el-header style="padding: 10px">
        <el-row>
          <el-col :span="10">
            <el-input v-model="title" placeholder="请输入标题">
              <template slot="prepend">标题</template>
            </el-input>
          </el-col>
          <el-col :span="8" style="padding-left: 10px">
            <el-input v-model="author" placeholder="请输入作者">
              <template slot="prepend">作者</template>
            </el-input>
          </el-col>
          <el-col :span="6" style="padding-left: 10px; text-align: right">
            <el-button style="margin-bottom: 10px" @click="launchOpen(1)"
              >保存草稿</el-button
            >
            <el-button type="primary" @click="launchOpen(2)"
              >发布文章</el-button
            >
          </el-col>
        </el-row>
      </el-header>
      <el-main style="padding: 10px">
        <TinymceEditor
          v-if="initSuccess"
          :content.sync="content"
          :contentText.sync="contentText"
        />
      </el-main>
    </el-container>
    <!-- launch弹窗 -->
    <el-dialog
      :title="launchViewTitle"
      :visible.sync="launchDialogVisible"
      width="30%"
      :before-close="launchClose"
      v-loading="loading"
    >
      <el-form ref="launchForm" :rules="rules" :model="row">
        <el-form-item label="文章封面" label-width="80px">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforePicUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章类型" label-width="80px" prop="type">
          <el-cascader
            ref="etCascader"
            v-model="row.type"
            :options="noEmptyChildrenTypeOption"
            :props="{
              label: 'title',
              value: 'code',
              multiple: true,
              checkStrictly: true,
            }"
            clearable
            filterable
            style="width: 100%"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="是否通知" label-width="80px" prop="alarm">
          <el-select
            v-model="row.alarm"
            placeholder="选择是否通知"
            style="margin-right: 10px; width: 100%"
          >
            <el-option label="不通知" :value="0"></el-option>
            <el-option label="需通知" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="摘要填写" label-width="80px" prop="intro">
          <el-input
            type="textarea"
            v-model="row.intro"
            placeholder="摘要：会在推荐、列表等场景外露，帮助读者快速了解内容，默认将正文前 180 字符键入摘要文本框"
            :maxlength="180"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="launchClose">取 消</el-button>
        <el-button type="primary" @click="launchConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { isStrEmpty } from "@/utils/util";
import { baseURL } from "@/api/request";
export default {
  //todo: 没有做到离开页面，检测内容是否保存的功能。。。
  // 因为是前端，不是我特别想钻研的方向，先搁置吧
  // 应该加个标识变量就好，需要监听内容是否改变 -- 240129

  data() {
    return {
      //初始值
      id: null,
      //文章用到的数据
      typeOptions: [],
      noEmptyChildrenTypeOption: [],
      alarm: null,
      title: "",
      author: "",
      status: null,
      //封面上传参数
      coverFile: null,
      imageUrl: null,
      //tinymce参数
      content: "",
      contentText: "",
      initSuccess: false,
      //其他
      loading: false,
      launchDialogVisible: false,
      launchViewTitle: "",
      launchCode: -1,
      //表单参数
      row: {},
      rules: {
        alarm: [
          { required: true, message: "请选择是否通知", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择文章类型", trigger: "change" },
        ],
      },
    };
  },
  props: {
    params: {
      type: Number,
      default: null,
    },
  },
  methods: {
    beforePicUpload(file) {
      this.coverFile = file;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const _base64 = reader.result;
        this.imageUrl = _base64; //将_base64赋值给图片的src，实现图片预览
      };
      return false;
    },
    async getEssayType() {
      await this.request
        .get("/essayType/getTreeOptions", {
          params: {
            parent: "-1",
            deleted: 0,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.typeOptions = res.data;
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    findEssayById() {
      this.request
        .get("/essay/findById", {
          params: {
            id: this.id,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            const typeArr = this.getEssayTypeTreeArrByStr(res.data.type);
            console.log(res.data);
            this.row = {
              alarm: res.data.alarm,
              type: typeArr,
              intro: res.data.intro,
            };
            this.title = res.data.title;
            this.author = res.data.author;
            this.status = res.data.status;
            this.content = res.data.content;
            this.imageUrl = baseURL + res.data.cover;
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
          this.initSuccess = true;
        })
        .catch((err) => {
          this.initSuccess = true;
        });
    },
    launchOpen(launchCode) {
      if (
        isStrEmpty(this.title) ||
        isStrEmpty(this.contentText) ||
        isStrEmpty(this.author)
      ) {
        this.$message({
          message: "请先完善标题、作者、内容等信息",
          type: "warning",
        });
        return;
      }
      this.launchCode = launchCode;
      if (this.launchCode == 2) {
        this.launchViewTitle = "发布文章";
      }
      if (this.launchCode == 1) {
        this.launchViewTitle = "保存草稿";
      }
      this.launchDialogVisible = true;
    },
    launchClose() {
      this.launchDialogVisible = false;
    },
    launchConfirm() {
      this.$refs["launchForm"].validate((valid) => {
        if (valid) {
          this.launchAll();
          this.launchClose();
        }
      });
    },
    //发布
    launchAll() {
      if (isStrEmpty(this.row.intro)) {
        this.row.intro = this.contentText.slice(0, 90);
      }
      this.$alert("是否确定发布", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            const formData = new FormData();
            formData.append("file", this.coverFile);
            formData.append("title", this.title);
            formData.append("author", this.author);
            formData.append("content", this.content);
            formData.append("type", this.getEssayTypeStrParam(this.row.type));
            formData.append("alarm", this.row.alarm);
            formData.append("intro", this.row.intro);
            formData.append("status", this.launchCode);
            var url = "/essay/add";
            if (this.id != null) {
              formData.append("id", this.id);
              url = "/essay/update";
            }
            this.loading = true;
            this.request
              .post(url, formData)
              .then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: res.msg,
                    type: "success",
                  });
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        },
      });
    },
    getNoEmptyChildrenTreeData(data) {
      for (let i = 0; data != undefined && i < data.length; i++) {
        if (data[i].children != undefined && data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getNoEmptyChildrenTreeData(data[i].children);
        }
      }
      return data;
    },
    getEssayTypeStrParam(typeArr) {
      let typeStrArr = [];
      for (let i = 0; typeArr != undefined && typeArr.length > i; i++) {
        let child = typeArr[i];
        typeStrArr.push(child[child.length - 1]);
      }
      return typeStrArr.join(",");
    },
    getEssayTypeTreeArrByStr(typeStr) {
      let codes = typeStr.split(",");
      let typeOptions = this.typeOptions;
      let nestedArray = [];
      function findParent(code, options) {
        for (let i = 0; i < options.length; i++) {
          let option = options[i];
          if (option.code === code) {
            return [option.code];
          } else if (option.children && option.children.length > 0) {
            let parent = findParent(code, option.children);
            if (parent) {
              parent.push(option.code);
              return parent;
            }
          }
        }
        return null;
      }
      for (let i = 0; i < codes.length; i++) {
        let code = codes[i];
        let parent = findParent(code, typeOptions);
        if (parent) {
          nestedArray.push(parent.reverse());
        }
      }
      return nestedArray;
    },
  },
  watch: {
    typeOptions: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.noEmptyChildrenTypeOption =
          this.getNoEmptyChildrenTreeData(newVal);
      },
    },
  },
  async created() {
    await this.getEssayType();
    // 初始化放在这里了，因为文章内的类型参数需要获取类型列表才可以初始化
    this.id = this.params;
    if (this.id != null) {
      this.findEssayById();
    } else {
      this.initSuccess = true;
    }
  },
};
</script>


<style>
.avatar-uploader {
  line-height: 0;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 90px;
  line-height: 80px !important;
  text-align: center;
}
.avatar {
  /* width: 160px; */
  width: auto; /* 宽度自适应 */
  height: 90px;
  display: block;
}
</style>